package com.usian.quartz;

import com.usian.mq.MQSender;
import com.usian.pojo.LocalMessage;
import com.usian.pojo.TbOrder;
import com.usian.redis.RedisClient;
import com.usian.service.LocalMessageService;
import com.usian.service.OrderService;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Date;
import java.util.List;

/**
 * @author chen
 * @date 2021/1/28 - 18:24 - 星期四
 * @project usian_parent
 * @package com.usian.quartz
 * @by GGbomd猪猪侠
 */
@Component
public class OrderQuartz implements Job {

    @Autowired
    private OrderService orderService;

    @Autowired
    private RedisClient redisClient;

    @Value("${ORDER_ID_KEY}")
    private String ORDER_ID_KEY;

    @Autowired
    private MQSender mqSender;

    @Autowired
    private LocalMessageService localMessageService;

    /**
     * 关闭超时订单
     */
    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        //解决quartz集群任务重复执行问题
        String ip = null;
        try {
            ip = InetAddress.getLocalHost().getHostAddress();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        if(redisClient.setnx(ORDER_ID_KEY,ip,30L)){
            //1、查询超时订单
            List<TbOrder> tbOrderList = orderService.selectOverTimeTbOrder();

            //2、关闭超时订单
            for (TbOrder tbOrder : tbOrderList) {
                orderService.updateOverTimeTbOrder(tbOrder);
                //3、把超时订单中的商品库存数量加回去
                orderService.updateTbItemByOrderId(tbOrder.getOrderId());
            }
            System.out.println("执行扫描本地消息表的任务...." + new Date());
            List<LocalMessage> localMessageList =
                    localMessageService.selectlocalMessageByStatus();
            for (int i = 0; i < localMessageList.size(); i++) {
                LocalMessage localMessage =  localMessageList.get(i);
                mqSender.sendMsg(localMessage);
            }
            //发送消息
            redisClient.del(ORDER_ID_KEY);
        }else{
            System.out.println("=================任务正在执行=======================");
        }
    }
}
